﻿/*
Copyright (c) 2015 Adrian Ghirvu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;

namespace XRTools
{
    public enum XRNodeType
    {
        UNKNOWN, NUMBER, IDENTIFIER, GUID, OPERATOR, FUNCTION, PARENTHESIS
    }

    public class XRNode
    {
        public XRNodeType type;
        public string value;
        public int precedence;
        public double sign;
        public XRNode parent;
        public List<XRNode> children;

        public XRNode(string token)
        {
            type = XRNodeType.UNKNOWN;
            value = String.Empty;
            precedence = 0;
            sign = 1;
            parent = null;
            children = new List<XRNode>();

            if (String.IsNullOrEmpty(token)) return;

            if (token == "(" || token == ")")
            {
                type = XRNodeType.PARENTHESIS;
                value = token;
                precedence = 1;
                return;
            }

            if (token[0] >= '0' && token[0] <= '9')
            {
                type = XRNodeType.NUMBER;
                value = token;
                precedence = 2;
                return;
            }
            if ((token[0] >= 'a' && token[0] <= 'z') || (token[0] >= 'A' && token[0] <= 'Z') || (token[0] == '_'))
            {
                type = XRNodeType.IDENTIFIER;
                value = token;
                precedence = 2;
                return;
            }
            if (token.Length == 38 && token[0] == '{' && token[token.Length - 1] == '}')
            {
                type = XRNodeType.GUID;
                value = token.Substring(1, 36);
                precedence = 2;
                return;
            }

            if (token == "*" || token == "/" || token == "?")
            {
                type = XRNodeType.OPERATOR;
                value = token;
                precedence = 3;
                return;
            }

            if (token == "+" || token == "-")
            {
                type = XRNodeType.OPERATOR;
                value = token;
                precedence = 4;
                return;
            }

            if (token == "<" || token == ">" || token == "<=" || token == ">=")
            {
                type = XRNodeType.OPERATOR;
                value = token;
                precedence = 5;
                return;
            }

            if (token == "==" || token == "<>")
            {
                type = XRNodeType.OPERATOR;
                value = token;
                precedence = 6;
                return;
            }

            if (token == "&")
            {
                type = XRNodeType.OPERATOR;
                value = token;
                precedence = 7;
                return;
            }

            if (token == "|")
            {
                type = XRNodeType.OPERATOR;
                value = token;
                precedence = 8;
            }
        }
    }

    public class XREvaluator
    {
        private List<string> ReadTokenBlock(List<string> tokens, ref int index)
        {
            List<string> list = new List<string>();
            if (tokens[index] == "(")
            {
                index++;
                int level = 1;
                while (level > 0 && index < tokens.Count)
                {
                    if (tokens[index] == "(") level++;
                    if (tokens[index] == ")") level--;
                    if (level > 0)
                    {
                        list.Add(tokens[index]);
                    }
                    index++;
                }
            }
            return list;
        }

        private List<string> SplitTokenBlock(List<string> tokens, ref int index)
        {
            List<string> list = new List<string>();
            int level = 0;
            while (index < tokens.Count)
            {
                if (tokens[index] == "(") level++;
                if (tokens[index] == ")") level--;
                if (level == 0 && tokens[index] == ";") break;
                list.Add(tokens[index]);
                index++;
            }
            return list;
        }

        private XRNode LookupTree(int precedence, XRNode current)
        {
            XRNode work = current;
            while (work != null && work.precedence <= precedence)
            {
                work = work.parent;                
            }
            return work;
        }

        private void LinkNode(ref XRNode root, ref XRNode current, ref XRNode node)
        {
            if (current == null)
            {
                root = node;
            }
            else
            {
                current.children.Add(node);
                node.parent = current;
            }
        }

        private void AddChild(ref XRNode parent, ref XRNode child)
        {
            parent.children.Add(child);
            child.parent = parent;
        }

        private XRNode CreateTree(List<string> tokens)
        {
            XRNode root = null;
            XRNode current = null;

            int index = 0;            
            while (index < tokens.Count)
            {
                XRNode node = new XRNode(tokens[index]);
                if(node.type == XRNodeType.UNKNOWN) continue;

                if (node.value == "(")
                {
                    List<string> list = ReadTokenBlock(tokens, ref index);
                    node = CreateTree(list);
                    LinkNode(ref root, ref current, ref node);
                    continue;
                }

                if (node.type == XRNodeType.IDENTIFIER && (node.value == "IF" || node.value == "ROUND") && index+1 < tokens.Count && tokens[index+1] == "(")
                {
                    node.type = XRNodeType.FUNCTION;
                    index++;
                    List<string> list = ReadTokenBlock(tokens, ref index);
                    int i = 0;
                    XRNode child = CreateTree(SplitTokenBlock(list, ref i));
                    AddChild(ref node, ref child);
                    i++;
                    child = CreateTree(SplitTokenBlock(list, ref i));
                    AddChild(ref node, ref child);
                    i++;
                    child = CreateTree(SplitTokenBlock(list, ref i));
                    AddChild(ref node, ref child);
                    LinkNode(ref root, ref current, ref node);
                    continue;
                }

                if (index == 0 && node.type == XRNodeType.OPERATOR && (node.value == "+" || node.value == "-"))
                {
                    double sgn = 1.0;
                    if (node.value == "-") sgn = -1.0;
                    index++;
                    node = new XRNode(tokens[index]) {sign = sgn};
                }

                if (node.type == XRNodeType.OPERATOR || node.type == XRNodeType.FUNCTION)
                {
                    if (root == null)
                    {
                        root = node;
                    }
                    else                    
                    {
                        if (root.type != XRNodeType.OPERATOR && root.type != XRNodeType.FUNCTION)
                        {
                            AddChild(ref node, ref root);
                            root = node;
                        }
                        else
                        {
                            XRNode entry = LookupTree(node.precedence, current);
                            if (entry == null)
                            {
                                AddChild(ref node, ref root);
                                root = node;
                            }
                            else
                            {
                                XRNode link = entry.children[entry.children.Count - 1];
                                AddChild(ref node, ref link);
                                entry.children.RemoveAt(entry.children.Count - 1);
                                AddChild(ref entry, ref node);
                            }
                        }
                    }
                    current = node;
                }

                if(node.type == XRNodeType.IDENTIFIER || node.type == XRNodeType.GUID || node.type == XRNodeType.NUMBER)
                {
                    LinkNode(ref root, ref current, ref node);
                }
                index++;
            }
            return root;
        }

        public XRNode Evaluate(string expression)
        {
            XRLexer lx = new XRLexer();
            if (!lx.Tokenize(expression) || lx.Tokens.Count < 1) return null;
            return CreateTree(lx.Tokens);
        }
    }
}
